<template>
  <div class="app-container">
    <el-container>
      <el-main>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="first">
            <el-form ref="queryParams" :model="queryParams.editForm" :rules="rules1">
              <el-row>
                <el-col :span="8">
                  <el-form-item label="车辆编号：" prop="id">
                    <el-input
                      v-if="isEdit && tab === 0"
                      v-model="queryParams.editForm.id"
                      disabled
                      style="width: 240px"
                      readonly
                    />
                    <span v-else>{{ queryParams.id }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="车牌号码：" prop="licensePlate">
                    <el-input
                      v-if="isEdit && tab === 0"
                      v-model="queryParams.editForm.licensePlate"
                      style="width: 240px"
                    />
                    <span v-else>{{ queryParams.licensePlate }}</span>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="车型名称：" prop="truckTypeName">
                    <el-input
                      v-if="isEdit && tab === 0"
                      v-model="queryParams.editForm.truckTypeName"
                      style="width: 240px"
                    />
                    <span v-else>{{ queryParams.truckTypeName }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="车辆体积：" prop="allowableVolume">
                    <el-input
                      v-if="isEdit && tab === 0"
                      v-model="queryParams.editForm.allowableVolume"
                      style="width: 240px"
                    >
                      <span slot="suffix">m³</span>
                    </el-input>
                    <span v-else>{{ queryParams.allowableVolume }} m³</span>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="车辆载重：" prop="allowableLoad">
                    <el-input
                      v-if="isEdit && tab === 0"
                      v-model="queryParams.editForm.allowableLoad"
                      style="width: 240px"
                    >
                      <span slot="suffix">吨</span>
                    </el-input>
                    <span v-else>{{ queryParams.allowableLoad }} 吨</span>
                  </el-form-item>
                </el-col>

                <el-col :span="8">
                  <el-form-item label="GPSID：" prop="deviceGpsId">
                    <el-input
                      v-if="isEdit && tab === 0"
                      v-model="queryParams.editForm.deviceGpsId"
                      style="width: 240px"
                    />
                    <span v-else>{{ queryParams.deviceGpsId }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <div class="photoBox">
                  图片信息
                  <template v-if="isEdit && tab === 0">
                    <!-- 处在编辑模式 -->
                    <template
                      v-if="!queryParams?.editForm?.picture?.length"
                    ><!-- 没有图片信息 -->
                      <img
                        src="https://yjy-slwl-oss.oss-cn-hangzhou.aliyuncs.com/2a6cbcb0-93d0-41a3-ae18-248ee68c1def.png"
                        alt=""
                        class="photo"
                      >
                      <img
                        src="https://yjy-slwl-oss.oss-cn-hangzhou.aliyuncs.com/95f1ad63-c8f0-4be3-a5e9-c3c9320de30f.png"
                        alt=""
                        class="photo"
                      >
                    </template>
                    <template v-else>
                      <!-- 拥有图片信息 -->
                      <div
                        v-for="(src, index) in queryParams.editForm.picture"
                        :key="index"
                        class="photo"
                      >
                        <transition name="el-zoom-in-top">
                          <img width="100%" height="100%" :src="src" alt="">
                        </transition>
                        <div class="handleBox">
                          <span>
                            <i
                              class="el-icon-zoom-in"
                              @click="showDialog(src)"
                            />
                            <i
                              class="el-icon-delete"
                              @click="deletePhoto(src)"
                            />
                          </span>
                        </div>
                      </div>
                    </template>
                    <el-upload
                      action=""
                      :http-request="uploadImage"
                      :show-file-list="false"
                      class="photo"
                      :before-upload="beforeAvatarUpload"
                    >
                      <i class="el-icon-upload2" />
                      <div class="el-upload__text">上传图片</div>
                    </el-upload>
                  </template>
                  <template v-else>
                    <!-- 未处于编辑模式 -->
                    <template v-if="!queryParams?.picture?.length">
                      <img
                        src=""
                        alt=""
                        class="photo"
                      >
                    </template>
                    <template v-else>
                      <div
                        v-for="(src, index) in queryParams.picture"
                        :key="index"
                        class="photo"
                      >
                        <img width="100%" height="100%" :src="src" alt="">
                        <div class="handleBox">
                          <i class="el-icon-zoom-in" @click="showDialog(src)" />
                        </div>
                      </div>
                    </template>
                  </template>
                </div>
              </el-row>
            </el-form>
          </el-tab-pane>
          <!-- 行驶证信息 -->
          <el-tab-pane label="行驶证信息" name="second">
            <el-form ref="driverLicense" class="driverLicense" :rules="rules2" :model="driverLicense.editForm">
              <el-row>
                <el-col :span="8">
                  <el-form-item
                    label="行驶证号码："
                    prop="transportCertificateNumber"
                  >
                    <el-input
                      v-if="isEdit && tab === 1"
                      v-model="
                        driverLicense.editForm.transportCertificateNumber
                      "
                      placeholder="请输入行驶证号"
                      style="width: 214px"
                    />
                    <span v-else>{{
                      driverLicense.transportCertificateNumber || "--"
                    }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="发动机号码：" prop="engineNumber">
                    <el-input
                      v-if="isEdit && tab === 1"
                      v-model="driverLicense.editForm.engineNumber"
                      placeholder="请输入发动机号码"
                      style="width: 214px"
                    />
                    <span v-else>{{ driverLicense.engineNumber || "--" }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="注册时间：" prop="registrationDate">
                    <el-date-picker
                      v-if="isEdit && tab === 1"
                      v-model="driverLicense.editForm.registrationDate"
                      type="date"
                      placeholder="请选择注册时间"
                      style="width: 214px"
                      value-format="yyyy-MM-dd"
                    />
                    <span v-else>{{
                      driverLicense.registrationDate || "--"
                    }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="强制报废日期：" prop="mandatoryScrap">
                    <el-date-picker
                      v-if="isEdit && tab === 1"
                      v-model="driverLicense.editForm.mandatoryScrap"
                      type="date"
                      placeholder="请选择强制报废日期"
                      style="width: 214px"
                      value-format="yyyy-MM-dd"
                    />
                    <span v-else>{{ driverLicense.mandatoryScrap }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="整备质量：" prop="overallQuality">
                    <el-input
                      v-if="isEdit && tab === 1"
                      v-model="driverLicense.editForm.overallQuality"
                      placeholder="请输入整备质量"
                      style="width: 214px"
                    ><span slot="suffix">吨</span>
                    </el-input>
                    <span v-else>{{ driverLicense.overallQuality }} 吨</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="检验有效期：" prop="expirationDate">
                    <el-date-picker
                      v-if="isEdit && tab === 1"
                      v-model="driverLicense.editForm.expirationDate"
                      type="date"
                      placeholder="请选择检验有效期"
                      style="width: 214px"
                      value-format="yyyy-MM-dd"
                    />
                    <span v-else>{{
                      driverLicense.expirationDate || "--"
                    }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="核定载质量：" prop="allowableWeight">
                    <el-input
                      v-if="isEdit && tab === 1"
                      v-model="driverLicense.editForm.allowableWeight"
                      placeholder="请输入核定载质量"
                      style="width: 214px"
                    >
                      <span slot="suffix">吨</span>
                    </el-input>
                    <span v-else>{{
                      driverLicense.allowableWeight || "--"
                    }} 吨</span>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="有效期：" prop="validityPeriod">
                    <el-date-picker
                      v-if="isEdit && tab === 1"
                      v-model="driverLicense.editForm.validityPeriod"
                      type="date"
                      placeholder="请选择行驶证有效期"
                      style="width: 214px"
                      value-format="yyyy-MM-dd"
                    />
                    <span v-else>{{ driverLicense.validityPeriod }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <div class="photoBox">
                  图片信息
                  <template v-if="isEdit && tab === 1">
                    <!-- 修改模式 -->
                    <template v-if="!driverLicense?.editForm?.picture?.length">
                      <!-- 没有图片信息 -->
                      <img
                        src="https://yjy-slwl-oss.oss-cn-hangzhou.aliyuncs.com/f5b1a839-88ab-4af4-aba4-8b23320098a8.png"
                        alt=""
                        class="photo"
                      >
                      <img
                        src="https://yjy-slwl-oss.oss-cn-hangzhou.aliyuncs.com/50dcaf77-01ae-424c-b4b2-2f5efb96791a.png"
                        alt=""
                        class="photo"
                      >
                    </template>
                    <template v-else>
                      <!-- 拥有图片信息 -->
                      <div
                        v-for="(src, index) in driverLicense.editForm.picture"
                        :key="index"
                        class="photo"
                      >
                        <transition name="el-zoom-in-top">
                          <img width="100%" height="100%" :src="src" alt="">
                        </transition>
                        <div class="handleBox">
                          <span>
                            <i
                              class="el-icon-zoom-in"
                              @click="showDialog(src)"
                            />
                            <i
                              class="el-icon-delete"
                              @click="deletePhoto(src)"
                            />
                          </span>
                        </div>
                      </div>
                    </template>
                    <el-upload
                      action=""
                      :http-request="uploadImage"
                      :show-file-list="false"
                      class="photo"
                      :before-upload="beforeAvatarUpload"
                    >
                      <i class="el-icon-upload2" />
                      <div class="el-upload__text">上传图片</div>
                    </el-upload>
                  </template>
                  <template v-else>
                    <template
                      v-if="!driverLicense?.picture?.length"
                    ><img
                      src=""
                      alt=""
                      class="photo"
                    ></template>
                    <template v-else>
                      <div
                        v-for="(src, index) in driverLicense.picture"
                        :key="index"
                        class="photo"
                      >
                        <img width="100%" height="100%" :src="src" alt="">
                        <div class="handleBox">
                          <i class="el-icon-zoom-in" @click="showDialog(src)" />
                        </div>
                      </div>
                    </template>
                  </template>
                </div>
              </el-row>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-main>
      <el-footer style="text-align: center; border-top: 1px solid #e5e7ec">
        <!-- 编辑状态 -->
        <div v-if="isEdit" style="text-algin: center">
          <el-button type="primary" @click="fnSave">保存</el-button>
          <el-button @click="fnCancel">取消</el-button>
        </div>
        <!-- 非编辑状态 -->
        <div v-else style="text-algin: center">
          <el-button type="primary" @click="fnEdit(titleInfo)">编辑</el-button>
        </div>
      </el-footer>
    </el-container>
    <el-dialog class="photoDetail" :visible.sync="dialogVisible">
      <img :src="magnifyPhoto" alt="">
      <i class="el-icon-close" @click="dialogVisible = false" />
    </el-dialog>
  </div>
</template>

<script>
import {
  editDriverAPI,
  editDriverLicenseAPI,
  imageUploadAPI
} from '@/api/employee'
import { getCarDetail, getDriverInfo } from '@/api/car'
export default {
  name: 'DriverDetails',
  data() {
    return {
      infoForm: {},
      activeName: 'first',
      dialogVisible: false,
      dialogImageUrl: '',
      isEdit: false,
      srcList: [],
      // 车辆详情
      queryParams: {},
      // 驾驶证信息数据
      driverLicense: {},
      magnifyPhoto: '', // 放大图片
      value1: '',
      titleInfo: 'queryParams',
      tab: 0,
      rules1: {
        id: [{ required: true, message: '车辆编号不能为空', trigger: 'blur' }],
        truckTypeName: [
          { required: true, message: '车型名称不能为空', trigger: 'blur' }
        ],
        licensePlate: [
          { required: true, message: '车牌号码不能为空', trigger: 'blur' }
        ],
        allowableLoad: [
          { required: true, message: '车辆载重不能为空', trigger: 'blur' }
        ],
        allowableVolume: [
          { required: true, message: '车辆体积不能为空', trigger: 'blur' }
        ],
        deviceGpsId: [
          { required: true, message: 'GPSID不能为空', trigger: 'blur' }
        ]
      },
      rules2: {
        transportCertificateNumber: [{ required: true, message: '行驶证号码不能为空', trigger: 'blur' }],
        engineNumber: [{ required: true, message: '发动机号码不能为空', trigger: 'blur' }],
        registrationDate: [{ required: true, message: '注册时间不能为空', trigger: 'blur' }],
        mandatoryScrap: [{ required: true, message: '强制报废日期不能为空', trigger: 'blur' }],
        overallQuality: [{ required: true, message: '整备质量不能为空', trigger: 'blur' }],
        expirationDate: [{ required: true, message: '检验有效期不能为空', trigger: 'blur' }],
        allowableWeight: [{ required: true, message: '核定载质量不能为空', trigger: 'blur' }],
        validityPeriod: [{ required: true, message: '有效期不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getCarDetail()
  },
  methods: {
    // 删除图片
    deletePhoto(src) {
      if (this.tab === 0) {
        this.queryParams.editForm.picture.splice(
          this.queryParams.editForm.picture.indexOf(src),
          1
        )
      } else {
        this.driverLicense.editForm.picture.splice(
          this.driverLicense.editForm.picture.indexOf(src),
          1
        )
      }
    },
    // 显示放大效果
    showDialog(src) {
      this.magnifyPhoto = src
      this.dialogVisible = true
    },
    // 上传之前的回调函数 , 做文件校验
    beforeAvatarUpload(file) {
      // 文件类型校验
      const fileTypeArr = ['image/jpeg', 'image/png', 'image/gif']
      const isJPG = fileTypeArr.includes(file.type)
      // 文件大小限制
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isJPG && isLt2M
    },
    async uploadImage(e) {
      // 首先判断是否图片已经上传了两张了
      let key = 'queryParams'
      if (this.tab === 1) {
        key = 'driverLicense'
      }
      if (this[key].editForm.picture.length >= 2) {
        return this.$message.error('最多上传2张图片')
      }
      const data = new FormData()
      data.append('file', e.file)
      const res = await imageUploadAPI(data)
      this[key].editForm.picture.push(res)
    },
    // 获取车辆基本信息
    async getCarDetail() {
      const res = await getCarDetail(this.$route.query.id)
      this.queryParams = res
      this.queryParams.picture = res.picture?.split(',') || []
    },
    // 切换tab栏
    handleClick(tab, event) {
      this.isEdit = false
      this.tab = 0
      if (tab.index === '1') {
        this.getDriverLicense()
        this.tab = 1
        this.titleInfo = 'driverLicense'
      } else {
        this.titleInfo = 'queryParams'
      }
    },
    // 编辑
    fnEdit(val) {
      this.$set(this[val], 'editForm', {})
      for (const key in this[val]) {
        if (key !== 'editForm') {
          if (key === 'picture') {
            this.$set(this[val].editForm, key, [])
          } else {
            this.$set(this[val].editForm, key, this[val][key])
          }
        }
      }
      this[val].picture.forEach((item) => {
        this[val].editForm.picture.push(item)
      })
      this.isEdit = true
    },
    // 保存
    async fnSave() {
      try {
        await this.$refs[this.titleInfo].validate()
      } catch {
        return this.$message.error('请按照提示信息填写表格')
      }
      if (this.titleInfo === 'queryParams') {
        if (this[this.titleInfo].editForm.picture.length < 1) {
          return this.$message.error('车辆信息照片至少上传一张')
        }
        await editDriverAPI(this.queryParams)
      } else {
        if (this[this.titleInfo].editForm.picture.length < 2) {
          return this.$message.error('行驶证照片必须上传两张')
        }
        await editDriverLicenseAPI(this.driverLicense.editForm)
      }
      for (const key in this[this.titleInfo].editForm) {
        if (key !== 'editForm') {
          this[this.titleInfo][key] = this[this.titleInfo].editForm[key]
        }
      }
      this[this.titleInfo].editForm.picture =
        this[this.titleInfo].editForm.picture.join(',')
      this.$message.success('修改成功')
      this.isEdit = false
    },
    // 取消
    fnCancel() {
      this.isEdit = false
      this.$refs[this.titleInfo].resetFields()
    },
    // 获取行驶证信息
    async getDriverLicense() {
      const res = await getDriverInfo(this.$route.query.id)
      this.driverLicense = res
      // console.log(res)
      this.driverLicense.picture = res.picture?.split(',') || []
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  // height: calc(100vh - 50px);
  padding-bottom: 0;
  display: flex;
  flex-direction: column;
  :deep(.el-form) {
    padding: 20px 40px;
    .el-input--suffix {
      .el-input__suffix {
        color: #000;
        padding-right: 1em;
      }
    }
    .photoBox {
      font-size: 14px;
      color: #606266;
      font-weight: 600;
      display: flex;
      .photo {
        margin-left: 20px;
        position: relative;
        width: 212px;
        height: 159px;
        overflow: hidden;
        border-radius: 4px;
        font-size: 14px;
        font-weight: 400;
        color: #363535;
        .el-upload {
          width: 100%;
          height: 100%;
          display: flex;
          flex-direction: column;
          align-content: space-around;
          flex-wrap: wrap;
          justify-content: center;
        }
        .handleBox {
          position: absolute;
          width: 100%;
          height: 100%;
          top: 0;
          left: 0;
          text-align: center;
          line-height: 159px;
          background-color: rgba($color: #000000, $alpha: 0.5);
          color: #fff;
          opacity: 0;
          cursor: pointer;
          i {
            &:nth-child(2) {
              margin-left: 35px;
            }
            font-size: 28px;
          }
        }
        &:hover .handleBox {
          opacity: 1;
        }
        .el-upload:hover {
          color: #e35f42;
        }
        i {
          font-size: 20px;
        }
      }
      .photo:nth-child(1) {
        margin-left: 60px;
      }
      div.photo {
        border: 1px dashed #d8dde3;
      }
    }
  }
  :deep(.el-container) {
    flex-grow: 1;
    background-color: #fff;
    .el-footer {
      height: 87px !important;
      .el-button {
        margin-top: 31px;
        padding: 10px 40px;
      }
    }
    // 基本信息
    // 行驶证信息
    .driverLicense {
      .el-form-item__label{
        min-width: 8em;
        text-align: left;
      }
    }
  }
  .footer {
    position: relative;
  }
  :deep(.el-tabs) {
    .el-tabs__nav {
      transform: translateX(30px) !important;
    }
    .el-tabs__item.is-active {
      font-size: 16px;
      font-weight: 600;
      color: #000;
    }
  }
  :deep(.el-dialog) {
    width: 600px;
    height: 600px;
    .el-dialog__header {
      display: none;
    }
    .el-dialog__body {
      padding: 0;
      position: relative;
    }
    img {
      width: 600px;
      height: 600px;
    }
    .el-icon-close {
      position: absolute;
      top: 5%;
      right: 5%;
      color: #909292;
      cursor: pointer;
      &:hover {
        color: #4f9cff;
      }
    }
  }
}
</style>
